import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.Point;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class Game extends JFrame implements MouseListener{
	Game(String s){
		super(s);
		
		
		playerWon = false;
		computerWon = false;
		
		board = new Board[2];
		setupBoard = false;
		start = true;
		lastClickedPosition = null;
		
		playerOne = new Player("0", "Player One");
		playerTwo = new Computer("1");
		
		this.setLayout(new BorderLayout());
		
		messager = new JLabel("Welcome to Battleship, click on the board to begins", JLabel.CENTER);
		messager.setPreferredSize(new Dimension(128, 128));
		
		
		JPanel emptySpace = new JPanel();
		emptySpace.setPreferredSize(new Dimension(64, 1));
		board[0] = new Board(true);
		board[0].addMouseListener(this);
		board[1] = new Board(false);
		
		add(board[0], BorderLayout.WEST);
		add(emptySpace, BorderLayout.CENTER);
		add(board[1], BorderLayout.EAST);
		add(messager, BorderLayout.SOUTH);
		
		board[0].addKeyListener(new CKey());

		
		
		pack();
	}
	public void mouseClicked(MouseEvent e) {
		if(e.getSource() instanceof Space){
			Space s = (Space)e.getSource();
			int x = s.getX() / Space.DEFAULT_SIZE;
			int y = s.getY() / Space.DEFAULT_SIZE;
			
			/*
			 * When we are just starting the game we want to make 
			 * sure the user interacts 
			 */
			if(start){
				start = false;
				setupBoard = true;

				String text = "Click on two points to place a ship.\nThe Current Ship is a " + board[0].getCurrentShipToLayDown();
				text += " and is " + String.valueOf(board[0].getCurrentShipToLayDownSize()) + " spaces long";
			}
			else if(setupBoard){;

				
			/* We need to send two clicks into setupNextShipAt. 
			 * So we grab the first click and put it into the lastPointPosition
			 * After the second click we null out the previous  
			 */
				if(lastClickedPosition == null){
					lastClickedPosition = new Point(x, y);
					// we need to update which ship the user is placing down.
					String text = "Click on two points to place a ship.\n The Current Ship is a " + board[0].getCurrentShipToLayDown();
					text += " and is " + String.valueOf(board[0].getCurrentShipToLayDownSize()) + " spaces long";
					messager.setText(text);
			/*
			 * We've clicked on another Space. If the next button click
			 * meets the right conditions we will be able to place the ship 
			 * on the board for the player.
			 */
				} else {
					if(board[0].setupNextShipAt(lastClickedPosition, new Point(x, y) )){
						Point[] p;
						p = playerTwo.setupNextShip();
						
						/*
						 * The player has successfully placed a Ship on the board.
						 * Now we will attempt to have the computer place a ship on 
						 * the board.
						 */
						while(!board[1].setupNextShipAt(p[0], p[1]) ){
							// If we failed placing the ship on the board we will 
							// get to this spot. 
							
							// We need to increment the Ships Left inside
							// the computer class because they setupNextShipAt 
							// decrements every time it is called.
							playerTwo.incShipsLeft();
							// We go ahead and get
							p = playerTwo.setupNextShip();
						}
						
					}
					// We will need to set last clicked Position null after the other click fail
					// or success. This gives the player to pick another two spots to place their ship.
					lastClickedPosition = null;
					
					
				}
				
				/*
				 * If we have 5 ships on the board we are 
				 * finished with setup and now we can start
				 * the game. 
				 */
				if(board[0].getNumOfShipsOnBoard() == 5){
					// We will no longer need to be clicking on 
					// the main board so we will remove it's mouse listener.
					board[0].removeMouseListener(this);
					
					// We will now need to start attacking the computer
					// so we will fire at his board and need an
					// active mouseListener on his board.
					board[1].addMouseListener(this);
					setupBoard = false;
					
					// We send the User a message that they are now
					// Hot and should fire on the enemy.
					String text = "Click on the Right board to fire";
					messager.setText(text);
				}


			} else {
				board[1].FireAt(new Point(x, y));
				// If the Player has killed the last ship
				// we have won the game. Good Job.
				if(board[1].areAllShipsDead()){
					board[1].removeMouseListener(this);
					messager.setText("Player Won");
				}
				Point p;
				// We need to keep firing until we get a
				// hit on either a ship or non previously
				// hit open sea.
				do{
					p = playerTwo.startTurn();
				} while(!board[0].FireAt(p) );

				if(board[0].areAllShipsDead()){
					board[0].removeMouseListener(this);
					messager.setText("Computer Won");
				}
			}
		}
		
	}

    // Non of these are needed
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e) {}
	
	// This is to check for the Ctrl-D
	// from the keyboard in order to 
	// trigger debug.
	class CKey extends java.awt.event.KeyAdapter {
		public void keyPressed(java.awt.event.KeyEvent event) {
		    if (event.getKeyCode() == java.awt.event.KeyEvent.VK_D)
		        if (event.isControlDown()) board[1].setDebugMode();
		}
	}

		
	private Board[] board;
	private Player playerOne;
	private Computer playerTwo;
	private JLabel messager; 
	private boolean playerWon;
	private boolean computerWon;
	private Point lastClickedPosition;
	
	private boolean start;
	private boolean setupBoard;
	
	public static void main(String[] args){
		Game game = new Game("Battleship");
		game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		game.setVisible(true);
	}



}
